package com.jsj.service.impl;

import com.jsj.dao.SiminfoDao;
import com.jsj.dao.StudentDao;
import com.jsj.dao.SubmissionDao;
import com.jsj.dao.SubmissionTopicDao;
import com.jsj.domain.Submission;
import com.jsj.domain.SubmissionTopic;
import com.jsj.domain.vo.TopicSubmissionVo;
import com.jsj.service.ISubmissionTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SubmissionTopicServiceImpl implements ISubmissionTopicService {

    @Autowired
    private SubmissionTopicDao submissionTopicDao;
    @Autowired
    private SiminfoDao siminfoDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private SubmissionDao submissionDao;

    @Override
    public SubmissionTopic querySubmissionTopicById(int id) {
        SubmissionTopic submissionTopic = submissionTopicDao.querySubmissionTopicById(id);
        if (submissionTopic != null) {
            submissionTopic.setSubmissions(submissionDao.querySubmissionBySubTopId(submissionTopic.getId()));
        }
        return submissionTopic;
    }

    @Override
    public List<TopicSubmissionVo> querySubmissionTopic(int topicId) {
        List<TopicSubmissionVo> topicSubmissionVos = submissionTopicDao.querySubmissionTopic(topicId);
        if (topicSubmissionVos != null) {
            for (TopicSubmissionVo topicSubmissionVo : topicSubmissionVos) {
                topicSubmissionVo.setNickName(studentDao.queryByUserName(topicSubmissionVo.getUserName()).getNickName());
            }
        }
        return topicSubmissionVos;
    }

    @Transactional
    @Override
    public Integer insertSubmissionTopic(SubmissionTopic submissionTopic) {
        if (submissionTopicDao.insertSubmissionTopic(submissionTopic) == 1) {
            for (Submission submission : submissionTopic.getSubmissions()) {
                submission.setSubtopId(submissionTopic.getId());
                submissionDao.insertSubmission(submission);
            }
            return 1;
        }
        return 0;
    }

    @Transactional
    @Override
    public Integer deleteSubmissionTopic(int id) {
        int sourceId;
        if (submissionTopicDao.deleteSubmissionTopic(id) == 1) {
            List<Submission> submissions = submissionDao.querySubmissionBySubTopId(id);
            if (submissions != null) {
                for (Submission submission : submissions) {
                    siminfoDao.deleteSiminfoBySourceId(submission.getId());
                }
                submissionDao.deleteSubmissionBySubTopId(id);
            }
            return 1;
        }
        return 0;
    }
}
